/**
 * Created by yijx on 2017/4/1.
 */
var rowSumNum = {};
var clickInputRow = -1;
//判断跳转到已发车界面是否向后台查询
var isQueryDoneTrans = true;

//表头宽度适应表体
function adaptTH() {
    $("table").children("thead").find("td,th").each(function () {
        var idx = $(this).index();
        var td = $(this).closest("table").children("tbody")
            .children("tr:first").children("td,th").eq(idx);
        $(this).width(td.width());
    })
};

//遮罩处理
function mask() {
    jQuery(document).ready(function ($) {
        $('.theme-login').click(function () {
            $('.theme-popover-mask').fadeIn(100);
            $('.theme-popover').slideDown(200);
        })
        $('.theme-poptit .close').click(function () {
            $('.theme-popover-mask').fadeOut(100);
            $('.theme-popover').slideUp(200);
        })
    })
}

$(function () {
    adaptTH();
    mask();
    allocation();
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        //如果激活的界面是"已发车"且未查询过或数据有更新，则进行查询
        if (e.target.hash == "#panel-547607") {
            var transBillId = $("#done tbody").children(".transBillCode").first().innerText;
            if (isQueryDoneTrans) {
                queryDoneTransBill();
            }
        }
        adaptTH();
    });

    var reqtruck = $("#reqtruck"),
        savebill = $("#savebill"),
        printbill = $("#printbill"),
        dispatch = $("#dispatch");

    reqtruck.on('click', function () {
        reqTruck();
    });
    savebill.on('click', function () {
        saveBill();
    });
    printbill.on('click', function () {
        printBill();
    });
    dispatch.on('click', function () {
        dispatchTruck();
    });

});

//查询货位
function allocation() {
    var rows = $("#req tbody tr");
    //根据物料查出货位信息
    searchAllocation();
}

//获得货位，
function gotAllocation(msg) {
    //界面填充货位
    var allocations = msg.allocation;
    var option = "";
    for (var x in allocations) {
        option += "<option value='" + x + "'>" + allocations[x] + "</option>";
    }
    $("#req tbody tr").each(function () {
        $(this).children(".allocation").children("select").append(option);
    });
}


//装车重量输入框点击，弹窗录入每次称重重量
function turckNumClick(clicked) {
    var input = clicked;
    clickInputRow = input.parentElement.parentElement.rowIndex - 1;
    //修改弹框遮罩标题
    $(".theme-popover h4.text-center")[0].innerText = "录入重量";
    //修改弹框遮罩内容
    var form = $(".theme-popbod.dform");
    form.empty();
    var matunit = $("#req tbody tr .trucknum .matunit").first().text();
    var weighNum = rowSumNum[clickInputRow];
    var result = "<ul class='list-group'>";
    var weighSum = 0;
    if (weighNum == null) {
        for (var i = 1; i < 6; i++) {
            result += "<li class='list-group-item'><div class='input-group weigh'>" +
                "<span class='input-group-addon'>" + i + ":</span>" +
                "<input class='form-control' placeholder='第" + i + "次称重' type='number'>" +
                "<span class='input-group-addon'>" + matunit + "</span></div></li>";
        }
    } else {
        for (var i = 1; i < weighNum.length + 1; i++) {
            if ("" != weighNum[i - 1]) {
                weighSum += parseFloat(weighNum[i - 1]);
            }
            result += "<li class='list-group-item'><div class='input-group weigh'>" +
                "<span class='input-group-addon'>" + i + ":</span>" +
                "<input class='form-control' placeholder='第" + i + "次称重' type='number' value='" + weighNum[i - 1] + "'>" +
                "<span class='input-group-addon'>" + matunit + "</span></div></li>";
        }
    }
    result += "<li class='divider'></li>";
    result += "<li class='list-group-item'><div class='input-group sum'>" +
        "<span class='input-group-btn'><button class='btn btn-default' type='button' onclick='truckSum(clickInputRow)'>+</button></span>" +
        "<input class='form-control' placeholder='总计' type='number' readonly='readonly' value='" + weighSum + "'>" +
        "<span class='input-group-addon'>" + matunit + "</span></div></li>";
    result += "<button class='btn btn-success' type='button' onclick='saveTruckNum(clickInputRow)'>确定</button>"
    result += "<button class='btn btn-success' type='button' onclick='cleanTruckNum(clickInputRow)'>清空</button>"
    result += "</ul>";
    form.append(result);
    //弹出遮罩
    $("#maskin").click();
    $(".input-group.weigh input").first().focus();
}

//合计称重重量
function truckSum(rowIndex) {
    //各称重重量
    var weighInput = $(".theme-popbod.dform .weigh input");
    rowSumNum[rowIndex] = new Array();
    var weighSum = 0;
    for (var x = 0; x < weighInput.length; x++) {
        var weighValue = weighInput.get(x).value;
        rowSumNum[rowIndex].push(weighValue);
        if ("" != weighValue) {
            weighSum += parseFloat(weighValue);
        }
    }
    //重量合计
    var sumInput = $(".theme-popbod.dform .sum input");
    sumInput.val(weighSum);
}

//清空称重重量
function cleanTruckNum(rowIndex) {
    $(".theme-popbod.dform input").val("");
    rowSumNum[rowIndex] = null;
    $("#req tbody tr .trucknum input")[rowIndex].value = 0;
}

//保存称重记录
function saveTruckNum(rowIndex) {
    var weighSum = $(".theme-popbod.dform .sum input").val();
    $("#req tbody tr .trucknum input")[rowIndex].value = weighSum;
    clickInputRow = -1;
    $('.theme-poptit .close').click();
}

//查询该备料申请已发车的转库单
function queryDoneTransBill() {
    //阻塞

    //参数
    var info = new Array();
    var rows = $("#req tbody tr");
    var transHeades = rows.children(".transHead");
    for (var i = 0; i < rows.length; i++) {
        var bill = new Object();
        bill.billid = transHeades.children(".reqid")[i].innerText;
        bill.rowno = transHeades.children(".rowno")[i].innerText;
        info.push(bill);
    }
    reqDoneTransBill(info);
}

//查询已发车转库单结果
function gotDoneTransBill(msg) {
    isQueryDoneTrans = false;
    if (msg == null || msg.length == 0) {
        return;
    }
    //从制作转库单界面拿到物料信息
    var matInfo = getMatInfo();
    //映射返回数据
    var rowMap = {};
    for (var row in matInfo) {
        rowMap[matInfo[row].reqid + matInfo[row].rowno] = matInfo[row];
    }

    //界面填充数据
    var doneTBody = $("#done tbody");
    var result = "";
    for (var x in msg) {
        var row = msg[x];
        var mat = rowMap[row.billid + row.rowno];
        if (mat == null) {
            continue;
        }
        doneTBody.empty();
        result += "<tr>";
        result += "<td class='transHead'>" +
            "<div class='transBillcode'>" + row.transBillCode + "</div>" +
            "<div class='reqid' style='display: none'>" + row.billid + "</div>" +
            "<div class='rowno' style='display: none'>" + row.rowno + "</div></td>" +
            "<td class='matname'>" + mat.matname + "</td>" +
            "<td class='matBatch'>" + mat.matBatch + "</td>" +
            "<td class='allocation'>" + mat.allocation + "</td>" +
            "<td class='reqnum'><div class='matnum'>" + mat.reqnum + "</div><div class='matunit'>" + mat.matunit + "</div></td>" +
            "<td class='trucknum'><div class='matnum'>" + row.truckNum + "</div><div class='matunit'>" + mat.matunit + "</div></td>";
        result += "</tr>";
    }
    doneTBody.append(result);
    adaptTH();
}

//取界面物料信息
function getMatInfo() {
    var matInfo = [];
    $("#req tbody tr").each(function () {
        var reqId = $(this).children(".transHead").children(".reqid").text();
        var rowNo = $(this).children(".transHead").children(".rowno").text();
        var mat = $(this).children(".matname").text();
        var allocation = $(this).children(".allocation").find("select option:selected").text();
        var matBatch = $(this).children(".matBatch").text();
        var reqNum = $(this).children(".reqnum").children(".matnum").text();
        var matunit = $(this).children(".reqnum").children(".matunit").text();
        var info = {
            reqid: reqId,
            rowno: rowNo,
            matname: mat,
            allocation: allocation,
            matBatch: matBatch,
            reqnum: reqNum,
            matunit: matunit
        }
        matInfo.push(info);
    });

    return matInfo;
}


//叫空车
function reqTruck() {
	$.ajax({
        type: "post",
        url: "reqTruck",
        traditional:true,
        data:"",
        dataType: "json",
        timeout: 30000,
        beforeSend: function (XMLHttpRequest) {
        },
        success: function (msg) {
            if(msg.success=="1"){
            	alert("要空车成功");
            }else{
            	var errinfo=msg.errinfo;
            	alert("要空车失败，系统错误："+errinfo);
            }
        },
        error: function(msg){
            alert("调用服务发生错误");
        }
    });
}
//叫空车结果
function truckResponse() {

}

//推后台转库单
function saveBill() {
    var info = new Array();
    var rows = $("#req tbody tr");
    var transHeades = rows.children(".transHead");
    var truckNums = rows.children(".trucknum").children("input");
    for (var i = 0; i < rows.length; i++) {
        var bill = new Object();
        bill.billid = transHeades.children(".reqid")[i].innerText;
        bill.rowno = transHeades.children(".rowno")[i].innerText;
        bill.truckNum = truckNums.get(i).value;
        info.push(bill);
    }
    saveBillRequst(info);
}
//后台推转库单成功,前台界面响应
function billSaved(msg) {
    if (msg.error != null) {
        alert(msg.error);
        $("#hint").text(msg.error);
        setTimeout("$('#hint').text('')",3000);
        return;
    }
    //回写转库单号、已转库重量
    var rows = msg.rows;
    if (null == rows || rows.length == 0) {
        return;
    }
    var trows = $("#req tbody tr");
    for (var x = 0; x < trows.length; x++) {
        var reqbillid = trows.find(".reqid").get(x).innerText;
        var reqrowno = trows.find(".rowno").get(x).innerText;
        for (var i in rows) {
            if (reqbillid == rows[i].billid && reqrowno == rows[i].rowno) {
                trows.find(".transBillcode").get(x).innerText = rows[i].transBillCode;
                trows.find(".transRowNo").get(x).innerText = rows[i].trasnRowNo;
                trows.find(".donenum").find(".matnum").get(x).innerText = rows[i].truckNum;
                var waitnum = trows.find(".waitnum").find(".matnum").get(x).innerText - rows[i].truckNum;
                trows.find(".waitnum").find(".matnum").get(x).innerText = waitnum >= 0 ? waitnum : 0;
            }
        }
    }
    //货位、装车重量不可编辑
    trows.find(".allocation select").attr("disabled", "true");
    trows.find(".trucknum input").attr("disabled", "true");
    //要空车按钮不可用
    $("#reqtruck").attr("disabled", "true");
    //保存按钮不可用
    $("#savebill").attr("disabled", "true");
    //返回按钮不可用
    $("#back").attr("disabled", "true");
    adaptTH();
}

//打印转库单号+行号等信息
function printBill() {
    window.print();
}

//转库单打印后回调
function  transBillPrinted(msg) {

}

//发满车
function dispatchTruck() {
    if ($(".transBillcode").get(0).innerText == "") {
        alert("保存转库单后才能发满车！");
        return;
    }
    var result = confirm("即将发满车，请确定已打印转库单、物料已装齐！");
    if (result) {
    	var tbcodes=new Array();
    	var trows = $("#req tbody tr");
        for (var x = 0; x < trows.length; x++) {
            var tbcode = trows.find(".transBillcode").get(x).innerText;
            if(tbcode){
            	tbcodes.push(tbcode);
            }
        }
        dispatch(tbcodes);

        isQueryDoneTrans = true;
        //清空装车重量
        rowSumNum = new Object();
        $("#req tbody tr .trucknum input").val("");
        //清空转库单号
        $("#req tbody tr .transBillcode").text("");
    }

}

//发满车回调
function truckDispatched(msg) {

}

